<template>
  <div class="coupon-exchange-page">
    <!-- 头部导航 -->
    <div class="page-header">
      <el-button
          type="text"
          icon="el-icon-arrow-left"
          class="back-btn"
          @click="$router.back()"
      ></el-button>
      <h1 class="page-title">优惠券兑换</h1>
    </div>

    <!-- 积分信息区 -->
    <div class="points-info">
      <div class="points-box">
        <p class="points-label">我的积分</p>
        <div class="points-value">
          <span class="num">{{ this.points }}</span>
          <span class="unit">积分</span>
        </div>
        <p class="points-desc">积分可兑换以下优惠券</p>
        <p class="points-desc">兑换完3天后过期</p>
      </div>
    </div>

    <!-- 可兑换优惠券列表 -->
    <div class="coupon-list-container">
      <h2 class="list-title">可兑换优惠券</h2>

      <div v-if="exchangeableCoupons.length > 0" class="coupon-grid">
        <el-card
            class="coupon-card"
            v-for="coupon in exchangeableCoupons"
            :key="coupon.id"
        >
          <div class="coupon-content">
            <!-- 优惠券左侧信息 -->
            <div class="coupon-left">
              <div class="discount-info">
                <div class="discount-info">
                  <span class="discount-value">{{ coupon.discount }}折</span>
                </div>
              </div>
              <p class="coupon-name">{{ coupon.name }}</p>
            </div>

            <div class="coupon-right">
              <p class="require-points">
                <i class="el-icon-credit-card"></i>
                {{ coupon.requiredPoints }}积分
              </p>
              <el-button
                  type="primary"
                  size="small"
                  class="exchange-btn"
                  :disabled="this.points < coupon.requiredPoints"
                  @click="handleExchange(coupon)"
              >
                兑换
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-state">
        <el-empty
            description="暂无可兑换的优惠券"
            :image="elEmptyImage"
        ></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import {queryAll} from "../api/coupon.js";
import axios from "axios";
import {add} from "../api/userCoupon.js";

export default {
  name: "Coupon",
  props: ['points'],
  data() {
    return {
      localPoints: this.points,
      exchangeableCoupons: [
        {
          id: 1,
          name: "8折通用券",
          requiredPoints: 300,
          discount: 8,
          status: 1
        },
      ]
    };
  },
  computed: {
    // Element UI 空状态图片
    elEmptyImage() {
      return this.$ELEMENT.isEmptyImage;
    }
  },
  methods: {
    async loadData() {
      let {data: data} = await queryAll()
      console.log(data)
      this.exchangeableCoupons = data.data
    }
    , async handleExchange(coupon) {
      // 1. 验证积分是否足够（coupon.requiredPoints 是兑换所需积分）
      if (this.points < coupon.requiredPoints) {
        this.$message.error("积分不足，无法兑换！");
        return; // 积分不够直接返回
      }

      try {
        // 2. 显示确认弹窗
        await this.$confirm(
            `确定要用 ${coupon.requiredPoints} 积分兑换【${coupon.name}】吗？`,
            "兑换确认",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        );

        // 3. 调用后端兑换接口（假设接口需要优惠券ID和用户ID）
        let {data: data} = await add({ id: coupon.id })
        console.log(data)
        // 4. 接口调用成功后处理
        if (data.code===200) {
          // 4.2 提示成功信息
          this.$message.success("兑换成功！优惠券已放入您的卡包");
          this.$router.push(`/wallet`); // 跳转到我的卡包
        } else {
          this.$message.error( "兑换失败，请稍后重试");
        }
      } catch (error) {
        // 5. 错误处理（包括用户取消弹窗、接口异常等）
        if (error === "cancel") {
          // 用户点击取消按钮
          this.$message.info("已取消兑换");
        } else {
          // 接口调用出错
          console.error("兑换接口异常：", error);
          this.$message.error("网络异常，兑换失败");
        }
      }
    }
  }
  , mounted() {
    this.loadData()
  }
};
</script>

<style scoped>
.coupon-exchange-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 30px;
}

/* 头部样式 */
.page-header {
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.back-btn {
  font-size: 16px;
  color: #333;
}

.page-title {
  flex: 1;
  margin: 0;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
}

/* 积分信息样式 */
.points-info {
  padding: 15px;
}

.points-box {
  background: linear-gradient(135deg, #42b983 0%, #359e75 100%);
  border-radius: 8px;
  padding: 20px 15px;
  color: #fff;
  text-align: center;
}

.points-label {
  margin: 0 0 10px;
  font-size: 14px;
  opacity: 0.9;
}

.points-value {
  margin-bottom: 10px;
}

.num {
  font-size: 32px;
  font-weight: bold;
  margin-right: 5px;
}

.unit {
  font-size: 16px;
  vertical-align: middle;
}

.points-desc {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
}

/* 优惠券列表样式 */
.coupon-list-container {
  padding: 0 15px;
}

.list-title {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.coupon-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.coupon-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.coupon-content {
  display: flex;
  align-items: center;
  padding: 15px;
}

.coupon-left {
  flex: 1;
  position: relative;
  padding-right: 15px;
}

.coupon-left::after {
  content: '';
  position: absolute;
  right: 0;
  top: 10%;
  height: 80%;
  width: 1px;
  background-image: linear-gradient(to bottom, transparent 5px, #eee 5px, #eee 10px, transparent 10px);
  background-size: 100% 15px;
}

.discount-info {
  margin-bottom: 5px;
}

.discount-sign {
  font-size: 16px;
  color: #e53e3e;
}

.discount-value {
  font-size: 24px;
  font-weight: bold;
  color: #e53e3e;
}

.coupon-name {
  margin: 0;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.coupon-right {
  flex: 0 0 100px;
  text-align: center;
  padding-left: 15px;
}

.require-points {
  margin: 0 0 10px;
  font-size: 12px;
  color: #666;
}

.exchange-btn {
  width: 100%;
}

/* 空状态样式 */
.empty-state {
  margin-top: 50px;
  padding: 30px 0;
  background-color: #fff;
  border-radius: 8px;
  text-align: center;
}
</style>